//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.yaukie.base.util;

import com.google.common.collect.Lists;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaukie.base.core.entity.SftpBean;

public class Sftp {
    private static final Logger log = LoggerFactory.getLogger(Sftp.class);
    private Session session;
    private Channel channel;
    private ChannelSftp chnSftp;
    public static final int FILE_TYPE = 1;
    public static final int DIR_TYPE = 2;
    private final SftpBean sftpBean;

    public Sftp(SftpBean sftpBean) {
        this.sftpBean = sftpBean;
    }

    public ChannelSftp open() throws JSchException {
        return this.connect();
    }

    private ChannelSftp connect() throws JSchException {
        JSch jsch = new JSch();
        if (StringUtils.isNotBlank(this.sftpBean.getPrivateKey())) {
            jsch.addIdentity(this.sftpBean.getPrivateKey());
        }

        this.session = jsch.getSession(this.sftpBean.getUserName(), this.sftpBean.getHost(), this.sftpBean.getPort());
        this.session.setPassword(this.sftpBean.getSecretKey());
        Properties sshConfig = new Properties();
        sshConfig.put("StrictHostKeyChecking", "no");
        this.session.setConfig(sshConfig);
        this.session.connect(20000);
        this.channel = this.session.openChannel("sftp");
        this.channel.connect();
        this.chnSftp = (ChannelSftp)this.channel;
        return this.chnSftp;
    }

    private void cd(String sftpPath) throws SftpException {
        this.chnSftp.cd(sftpPath);
    }

    private String pwd() throws SftpException {
        return this.chnSftp.pwd();
    }

    public List<Map<String, String>> listFiles(String directory, int fileType) throws SftpException {
        List<Map<String, String>> fileList = Lists.newArrayList();
        if (this.isDirExist(directory)) {
            Vector<?> vector = this.chnSftp.ls(directory);
            Iterator var6 = vector.iterator();

            while(var6.hasNext()) {
                Object obj = var6.next();
                String str = obj.toString().trim();
                int tag = str.lastIndexOf(":") + 3;
                String strName = str.substring(tag).trim();
                boolean itExist = this.isDirExist(directory + "/" + strName);
                HashMap dirMap;
                if (fileType == 1 && !itExist) {
                    dirMap = new HashMap();
                    dirMap.put("id", CodeUtil.getInstance().encode(strName));
                    dirMap.put("pId", CodeUtil.getInstance().encode(directory));
                    dirMap.put("name", strName);
                    dirMap.put("path", directory + "/" + strName);
                    fileList.add(dirMap);
                }

                if (fileType == 2 && itExist) {
                    dirMap = new HashMap();
                    if (!strName.equals(".") && !strName.equals("..")) {
                        dirMap.put("id", CodeUtil.getInstance().encode(directory + "/" + strName));
                        dirMap.put("pId", CodeUtil.getInstance().encode(directory));
                        dirMap.put("name", strName);
                        dirMap.put("path", directory + "/" + strName);
                        fileList.add(dirMap);
                    }
                }
            }
        }

        return fileList;
    }

    private boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;

        try {
            SftpATTRS sftpATTRS = this.chnSftp.lstat(directory);
            isDirExistFlag = true;
            return sftpATTRS.isDir();
        } catch (Exception var4) {
            if (var4.getMessage().toLowerCase().equals("no such file")) {
                isDirExistFlag = false;
            }

            return isDirExistFlag;
        }
    }

    public InputStream getFile(String sftpFilePath) throws SftpException {
        return this.isFileExist(sftpFilePath) ? this.chnSftp.get(sftpFilePath) : null;
    }

    public InputStream getInputStreamFile(String sftpFilePath) throws SftpException {
        return this.getFile(sftpFilePath);
    }

    public ByteArrayInputStream getByteArrayInputStreamFile(String sftpFilePath) throws SftpException, IOException {
        if (this.isFileExist(sftpFilePath)) {
            byte[] srcFtpFileByte = this.inputStreamToByte(this.getFile(sftpFilePath));
            ByteArrayInputStream srcFtpFileStreams = new ByteArrayInputStream(srcFtpFileByte);
            return srcFtpFileStreams;
        } else {
            return null;
        }
    }

    public String delFile(String sftpFilePath) throws SftpException {
        String retInfo;
        if (this.isFileExist(sftpFilePath)) {
            this.chnSftp.rm(sftpFilePath);
            retInfo = "1:File deleted.";
        } else {
            retInfo = "2:Delete file error,file not exist.";
        }

        return retInfo;
    }

    public void moveFile(String srcSftpFilePath, String distSftpFilePath, String fileNameTag) throws SftpException, IOException {
        boolean fileExist = this.isFileExist(srcSftpFilePath);
        boolean dirExist = this.isDirExist(distSftpFilePath);
        if (fileExist) {
            if (!dirExist) {
                this.createDir(distSftpFilePath);
            }

            String fileName = srcSftpFilePath.substring(srcSftpFilePath.lastIndexOf("/"));
            ByteArrayInputStream srcFtpFileStreams = this.getByteArrayInputStreamFile(srcSftpFilePath);
            if (StringTools.isNotBlank(fileNameTag)) {
                fileName = String.format("%s.%s", fileName, fileNameTag);
            }

            this.chnSftp.put(srcFtpFileStreams, distSftpFilePath + fileName);
            this.chnSftp.rm(srcSftpFilePath);
        }
    }

    public void copyFile(String srcSftpFilePath, String distSftpFilePath) throws SftpException, IOException {
        boolean fileExist = this.isFileExist(srcSftpFilePath);
        boolean dirExist = this.isDirExist(distSftpFilePath);
        if (fileExist) {
            if (!dirExist) {
                this.createDir(distSftpFilePath);
            }

            String fileName = srcSftpFilePath.substring(srcSftpFilePath.lastIndexOf("/"));
            ByteArrayInputStream srcFtpFileStreams = this.getByteArrayInputStreamFile(srcSftpFilePath);
            this.chnSftp.put(srcFtpFileStreams, distSftpFilePath + fileName);
        }
    }

    public void createDir(String sftpDirPath) throws SftpException {
        this.cd("/");
        if (!this.isDirExist(sftpDirPath)) {
            String[] pathStr = sftpDirPath.split("/");
            String[] var3 = pathStr;
            int var4 = pathStr.length;

            for(int var5 = 0; var5 < var4; ++var5) {
                String path = var3[var5];
                if (!path.equals("")) {
                    if (this.isDirExist(path)) {
                        this.cd(path);
                    } else {
                        this.chnSftp.mkdir(path);
                        this.chnSftp.cd(path);
                    }
                }
            }

            this.cd("/");
        }
    }

    public boolean isFileExist(String srcSftpFilePath) {
        boolean isExitFlag = false;
        if (this.getFileSize(srcSftpFilePath) >= 0L) {
            isExitFlag = true;
        }

        return isExitFlag;
    }

    public long getFileSize(String srcSftpFilePath) {
        long fileSize;
        try {
            SftpATTRS sftpATTRS = this.chnSftp.lstat(srcSftpFilePath);
            fileSize = sftpATTRS.getSize();
        } catch (Exception var5) {
            fileSize = -1L;
            if (var5.getMessage().toLowerCase().equals("no such file")) {
                fileSize = -2L;
            }
        }

        return fileSize;
    }

    public void close() {
        if (this.channel.isConnected()) {
            this.channel.disconnect();
        }

        if (this.session.isConnected()) {
            this.session.disconnect();
        }

    }

    public byte[] inputStreamToByte(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();

        int ch;
        while((ch = inputStream.read()) != -1) {
            bytestream.write(ch);
        }

        byte[] imgData = bytestream.toByteArray();
        bytestream.close();
        return imgData;
    }

    public static boolean upload(String directory, File uploadFile, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            FileInputStream fileInputStream = new FileInputStream(uploadFile);
            sftp.put(fileInputStream, uploadFile.getName() + ".tmp");
            fileInputStream.close();
            sftp.rename(uploadFile.getName() + ".tmp", uploadFile.getName());
            return true;
        } catch (SftpException var4) {
            if (mkdir(directory, sftp) && upload(directory, uploadFile, sftp)) {
                return true;
            }
        } catch (IOException var5) {
            var5.printStackTrace();
        }

        log.info("**********文件" + uploadFile.getName() + "上传失败**********");
        return false;
    }

    public static File download(String directory, String downloadFile, String saveFile, ChannelSftp sftp) {
        FileOutputStream fileOutputStream = null;

        File var6;
        try {
            File file = new File(saveFile);
            fileOutputStream = new FileOutputStream(file);
            sftp.cd(directory);
            sftp.get(downloadFile, fileOutputStream);
            var6 = file;
            return var6;
        } catch (Exception var16) {
            log.error(var16.getMessage());
            var6 = null;
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return var6;
    }

    public static boolean mkdir(String directory, ChannelSftp sftp) {
        try {
            log.info("**********目录{" + directory + "}不存在，即将创建**********");
            String[] dir = directory.split("/");

            int i;
            for(i = 0; i < dir.length; ++i) {
                try {
                    sftp.cd(dir[i]);
                } catch (Exception var5) {
                    sftp.mkdir(dir[i]);
                    sftp.cd(dir[i]);
                }
            }

            while(i-- != 0) {
                sftp.cd("..");
            }

            log.info("**********目录{" + directory + "}创建完成**********");
            return true;
        } catch (SftpException var6) {
            var6.printStackTrace();
            log.info("**********目录{" + directory + "}创建失败**********");
            return false;
        }
    }
}
